<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/16
 * Time: 11:07
 */

namespace app\admin\service;


use app\model\ManagerModel;
use app\model\ManagerRoleModel;
use think\facade\Db;

class ManagerService
{
    protected $model;

    public function __construct()
    {
        $this->model = new ManagerModel();
    }

    /**
     * 平台账户创建
     * @param $data
     * @return bool
     */
    public function save($data) {
        return $this->model->save($data);
    }

    /**
     * 平台账户查询
     * @param $data
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function findAll($data) {
        $list = $this->model->field('id,username,sex,phone,email,status,last_login_ip,login_times,remark,create_time,update_time')
            ->order('id', 'asc')
            ->paginate($data['list_rows']);
        return $list;
    }

    /**
     * 平台账户编辑
     * @param $id
     * @param $data
     * @return ManagerModel
     */
    public function update($id, $data) {
        return $this->model->where('id', $id)->update($data);
    }

    /**
     * 平台账户删除
     * @param $id
     * @return int
     */
    public function delete($id) {
        // 启动事务
        $db = new Db();
        $db->startTrans();
        try {
            $this->model->where('id', $id)->delete();
            (new ManagerRoleModel())->where('manager_id', $id)->delete();
            // 提交事务
            $db->commit();
            return 1;
        } catch (\Exception $e) {
            // 回滚事务
            $db->rollback();
            return 0;
        }
    }

    /**
     * 用户登陆
     * @param $data
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login($data) {
        $data['password'] = md5($data['password']);
        $data['status'] = 10;
        return $this->model->field('id,username,login_times')->where($data)->find();
    }
}